<?php
//自定义常量
define('DS', DIRECTORY_SEPARATOR);


use think\facade\Route;
use think\route\Url as UrlBuild;
use think\helper\Str;



// 应用公共文件
/**
 * 添加数据表前缀
 */
if( !function_exists('addTablePrefix') ){
    function addTablePrefix(string $name) :string {
        //获取配置的前缀
        return config('database.connections.mysql.prefix') . $name;
    }
}

/**
 * 获取项目上传的路径和url
 */
if (!function_exists('showImg')) {
    function showImg(string $path = ''){
        return config('filesystem.disks.public.url') . '/' .$path;

    }
}

/**
 * 截取多字节字符串
 */
if(!function_exists('truncate_utf8_string')){
    function truncate_utf8_string($string, $length, $etc = '...')
    {
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++)
        {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))
            {
                if ($length < 1.0)
                {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            }
            else
            {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen)
        {
            $result .= $etc;
        }
        return $result;
    }
}

/**
 * 去除字符串中的html及空白
 */
if (!function_exists('cutstr_html')){
    function cutstr_html($string){

        $string = strip_tags($string);

        $string = trim($string);

        $string = preg_replace("/[\n\r\t]/","",$string);

        return trim($string);
    }
}

/**
 * 获取字符串中的图片列表
 */
if (!function_exists('fetchImages')){
    function fetchImages($content, $prefix=''){
        if (empty($content)) return [];

        $images = [];
        $pattern='/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
        preg_match_all($pattern,$content,$res);

        //代表匹配到图片了，截取字符串，获取图片名称即可
        if(count($res[1]) > 0){
            foreach($res[1] as $v){
                if(strpos($v, $prefix) === 0){
                    $images[]=$v;
                }
            }
        }
        return $images;
    }
}
/**
 * 重写url函数
 */
if (!function_exists('url')) {
    /**
     * Url生成
     * @param string      $url    路由地址
     * @param array       $vars   变量
     * @param bool|string $suffix 生成的URL后缀
     * @param bool|string $domain 域名
     * @return UrlBuild
     */
    function url(string $url = '', array $vars = [], $suffix = true, $domain = false): UrlBuild
    {
        $url = Route::buildUrl($url, $vars)
            ->suffix($suffix)
            ->domain($domain);

        //是否配置了入口脚本
        if($root = config('route.root_file','')){
            $url = Str::startsWith((string) $url, $root) ? $url : $url->root($root);
        }

        return $url;
    }
}

/**
 * 输出相对时间
 */
if (!function_exists('absoluteTime')) {
    /**
     * 输出相对时间
     * @return string
     */
    function absoluteTime($date): string
    {

        $diff = time() - (strtotime($date) ?: $date);
        if ($diff<60)
            return $diff."秒前";

        $diff = round($diff/60);
        if ($diff<60)
            return $diff."分钟前";

        $diff = round($diff/60);
        if ($diff<24)
            return $diff."小时前";

        $diff = round($diff/24);
        if ($diff<7)
            return $diff."天前";
        $diff = round($diff/7);
        if ($diff<4)
            return $diff."星期前";

        return "on ".date("F j, Y", strtotime($date) ?: $date);
    }
}

/**
 * 输出json
 */
if (!function_exists('jsonStr')) {
    /**
     * 输出相对时间
     * @params array $data
     * @return string
     */
    function jsonStr(array $data): string
    {
        return json_encode($data, JSON_UNESCAPED_UNICODE );
    }
}

/**
 * 获取客户端浏览器
 */
if (!function_exists('getBrowser')){
    //获取用户浏览器类型
    function getBrowser(){
        $agent=$_SERVER["HTTP_USER_AGENT"] ?? '';
        if(strpos($agent,'MSIE')!==false || strpos($agent,'rv:11.0')) //ie11判断
            return "ie";
        else if(strpos($agent,'Firefox')!==false)
            return "firefox";
        else if(strpos($agent,'Chrome')!==false)
            return "chrome";
        else if(strpos($agent,'Opera')!==false)
            return 'opera';
        else if((strpos($agent,'Chrome')==false)&&strpos($agent,'Safari')!==false)
            return 'safari';
        else
            return 'unknown';
    }
}